const http = require("http");
const https = require("https");
const url = require("url");

http
  .createServer((req, res) => {
    const urlObj = url.parse(req.url, true);

    res.writeHeader(200, {
      "Content-Type": "application/json;charset=utf-8",
      //cors头
      "access-control-allow-origin": "*",
    });
    switch (urlObj.pathname) {
      case "/api/aaa":
        //客户端身份
        //这边不要直接传res参数，耦合性太高，可以用回调函数异步解耦
        httpPost((data) => {
          res.end(data);
        });
        break;
      default:
        res.end("404");
    }
  })
  .listen(5001, () => {
    console.log("post server start success");
  });

function httpPost(cb) {
  let data = "";
  const options = {
    hostname: "www.xiaomiyoupin.com",
    post: "443",
    path: "/mtop/mf/resource/data/list",
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      // "Content-Type": "x-www-form-urlencoded"
    },
  };
  const req = https.request(options, (res) => {
    res.on("data", (chunk) => {
      data += chunk;
    });
    res.on("end", () => {
      console.log("222", data);
      cb(data);
    });
  });

  // req.write("name=kerwin&age=18")
  req.write(JSON.stringify([{}, "pc_top_list"]));
  req.end();
}
